package body MIDI.Meta_Events is

   function To_Microseconds (T : Meta_Tempo) return Uint32_be
   is
   begin
      return Uint32_be(T.B1) * 256 * 256 + Uint32_be(T.B2) * 256 + Uint32_be(T.B3);
   end To_Microseconds;

   function To_Tempo (Microseconds_Per_Beat : Uint32_be) return Meta_Tempo
   is
      r : Uint32_be := Microseconds_Per_Beat and 16#00FF_FFFF#;
      t : Meta_Tempo;
   begin
      t.B1 := Uint8_t(r / 256 / 256);
      t.B2 := Uint8_t(r / 256 mod 256);
      t.B3 := Uint8_t(r mod 256); 
      return t;
   end To_Tempo;

   function To_BPM (T : Meta_Tempo) return Uint16_be
   is
      ms_per_minute : constant := 60 * 1000 * 1000;
      ms_per_beat   : Uint32_be := To_Microseconds(T);
   begin
      return Uint16_be(ms_per_minute / ms_per_beat);
   end To_BPM;

   function To_Tempo (BPM : Uint16_be) return Meta_Tempo
   is
      ms_per_minute : constant := 60 * 1000 * 1000;
      ms_per_beat   : Uint32_be := ms_per_minute / Uint32_be(BPM);
   begin
      return To_Tempo(ms_per_beat);
   end To_Tempo;

end MIDI.Meta_Events;
